import { FC, useCallback, useState } from 'react';
import './index.css';
import { DEFAULT_APP_URL, STORAGE_KEY } from '../../defined/app';

const Setting: FC = () => {
  const [appUrl, setAppUrl] = useState(localStorage.getItem(STORAGE_KEY.APP_URL) || DEFAULT_APP_URL);
  const handleChange: React.ChangeEventHandler<HTMLTextAreaElement> = useCallback((e) => {
    setAppUrl(e.target.value);
  }, []);

  const handleClick = useCallback(() => {
    if (!/^https?:\/\//.test(appUrl)) {
      return;
    }
    localStorage.setItem(STORAGE_KEY.APP_URL, appUrl);
    location.href = appUrl;
  }, [appUrl]);

  const handleNavToDefaultUrl = useCallback(() => {
    setAppUrl(DEFAULT_APP_URL);
    localStorage.setItem(STORAGE_KEY.APP_URL, DEFAULT_APP_URL);
    location.href = DEFAULT_APP_URL;
  }, []);

  return (
    <div className="setting-page">
      <textarea className="inp" placeholder="请输入网址" value={appUrl} onChange={handleChange} />
      <button className="btn" onClick={handleClick}>跳转</button>
      <button className="btn link" onClick={handleNavToDefaultUrl}>跳转到默认网址</button>
    </div>
  );
}

export default Setting;